import json
import logging

from django.views import View
from django.http import JsonResponse
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import extend_schema, OpenApiParameter
from rest_framework.response import Response
from rest_framework.views import APIView

from app.models import MerchantInfo, User
from app.services.dish_service import DishService
from middleware.util import make_response
logger = logging.getLogger(__name__)
from middleware.util import  AUTH_HEADER_PARAM
@extend_schema(
    tags=["菜品管理"],
    summary="上传新菜品（商家专用）",
    parameters=[AUTH_HEADER_PARAM],
    request={
        "application/json": {
            "example": {
                "dish_name": "宫保鸡丁",
                "price": 28.5,
                "category_id": "abcd1234-5678-90ef-ghij-klmnopqrstuv",
                "customization_options": {"辣度": ["微辣", "中辣", "重辣"]},
                "stock": 100,
                "status": "on_shelf",
                "images": [
                    {"data": "base64_string", "mime_type": "image/png"},
                    {"data": "base64_string", "mime_type": "image/webp"}
                ]
            }
        }
    }
)
class UploadDishView(APIView):
    def post(self, request):
        """
        接口：上传新菜品（支持多图）
        请求头需包含 Authorization: Bearer <token>
        请求体示例：
        {
          "dish_name": "宫保鸡丁",
          "price": 28.5,
          "category_id": "abcd1234-5678-90ef-ghij-klmnopqrstuv",
          "customization_options": {"辣度": ["微辣", "中辣", "重辣"]},
          "stock": 100,
          "images": [
            { "data": "base64_string", "mime_type": "image/png" },
            { "data": "base64_string", "mime_type": "image/webp" }
          ]
        }
        """
        try:
            user_id = getattr(request, 'user_id', None)
            role = getattr(request, 'role', None)

            if not user_id or role != 'merchant':
                return make_response(code=403, message="权限不足")

            try:
                user = User.objects.get(id=user_id)
                merchant_info = MerchantInfo.objects.get(merchant_id=user_id)
            except (User.DoesNotExist, MerchantInfo.DoesNotExist):
                return make_response(code=403, message="您不是合法的商家用户")

            data = json.loads(request.body)

            dish_name = data.get("dish_name")
            price = data.get("price")
            category_id = data.get("category_id")
            customization_options = data.get("customization_options")
            stock = data.get("stock", 0)
            status = data.get("status", "on_shelf")
            images = data.get("images", [])

            return DishService.upload_dish(
                merchant_id=merchant_info.merchant_id,
                dish_name=dish_name,
                price=price,
                category_id=category_id,
                customization_options=customization_options,
                stock=stock,
                status=status,
                images=images
            )

        except json.JSONDecodeError:
            return Response({
                "code": 400,
                "message": "请求体格式错误"
            }, status=400)

        except Exception as e:
            return Response({
                "code": 500,
                "message": f"系统错误：{str(e)}"
            }, status=500)

    # app/views/dish_views.py

@extend_schema(
    tags=["菜品管理"],
    summary="更新菜品信息（商家专用）",
    parameters=[AUTH_HEADER_PARAM],
    request={
        "application/json": {
            "example": {
                "dish_name": "宫保鸡丁",
                "price": 29.5,
                "category_id": "xxxx1234-5678-90ef-ghij-klmnopqrstuv",
                "customization_options": {"辣度": ["微辣", "中辣"]},
                "stock": 80,
                "status": "off_shelf",
                "images": [
                    {"data": "base64_string", "mime_type": "image/png"}
                ]
            }
        }
    }
)
class UpdateDishView(APIView):
    def put(self, request, dish_id):
        """
        接口：更新菜品信息 + 图片
        URL 示例：/merchant/dish/update/abcd1234-5678-90ef-ghij-klmnopqrstuv/
        请求头需包含 Authorization: Bearer <token>
        请求体示例：
        {
          "dish_name": "宫保鸡丁",
          "price": 29.5,
          "category_id": "xxxx1234-5678-90ef-ghij-klmnopqrstuv",
          "customization_options": {"辣度": ["微辣", "中辣"]},
          "stock": 80,
          "status": "on_shelf",
          "images": [
            { "data": "base64_string", "mime_type": "image/png" },
            { "data": "base64_string", "mime_type": "image/webp" }
          ]
        }
        """
        try:
            user_id = getattr(request, 'user_id', None)
            role = getattr(request, 'role', None)

            if not user_id or role != 'merchant':
                return make_response(code=403, message="权限不足")

            try:
                user = User.objects.get(id=user_id)
                merchant_info = MerchantInfo.objects.get(merchant_id=user_id)
            except (User.DoesNotExist, MerchantInfo.DoesNotExist):
                return make_response(code=403, message="您不是合法的商家用户")

            data = json.loads(request.body)

            return DishService.update_dish(
                dish_id=dish_id,
                merchant_id=merchant_info.merchant_id,
                dish_name=data.get("dish_name"),
                price=data.get("price"),
                category_id=data.get("category_id"),
                customization_options=data.get("customization_options"),
                stock=data.get("stock"),
                status=data.get("status"),
                images=data.get("images")
            )

        except json.JSONDecodeError:
            return Response({
                "code": 400,
                "message": "请求体格式错误"
            }, status=400)

        except Exception as e:
            return Response({
                "code": 500,
                "message": f"系统错误：{str(e)}"
            }, status=500)

@extend_schema(
    tags=["菜品管理"],
    summary="更新菜品库存（商家专用）",
    parameters=[AUTH_HEADER_PARAM],
    request={
        "application/json": {
            "example": {
                "stock": 50
            }
        }
    }
)
class UpdateDishStockView(APIView):
    def put(self, request, dish_id):
        """
        接口：更新菜品库存
        URL 示例：/merchant/dish/update-stock/abcd1234-5678-90ef-ghij-klmnopqrstuv/
        请求头需包含 Authorization: Bearer <token>
        请求体示例：
        {
          "stock": 50
        }
        """
        try:
            user_id = getattr(request, 'user_id', None)
            role = getattr(request, 'role', None)

            if not user_id or role != 'merchant':
                return make_response(code=403, message="权限不足")

            try:
                user = User.objects.get(id=user_id)
                merchant_info = MerchantInfo.objects.get(merchant_id=user_id)
            except (User.DoesNotExist, MerchantInfo.DoesNotExist):
                return make_response(code=403, message="您不是合法的商家用户")

            data = json.loads(request.body)
            new_stock = data.get("stock")

            return DishService.update_dish_stock(
                dish_id=str(dish_id),  # 确保是字符串格式
                merchant_id=str(merchant_info.merchant_id),
                new_stock=new_stock
            )

        except json.JSONDecodeError:
            return Response({
                "code": 400,
                "message": "请求体格式错误"
            }, status=400)

        except Exception as e:
            return Response({
                "code": 500,
                "message": f"系统错误：{str(e)}"
            }, status=500)
@extend_schema(
    tags=["菜品管理"],
    parameters=[AUTH_HEADER_PARAM],
    summary="获取当前商家所有分类及对应菜品（仅返回 ID 和名称）"
)
class ListCategoriesWithDishesView(APIView):
    def get(self, request):
        """
        接口：获取当前商家所有分类及对应菜品（仅返回 ID 和名称）
        需要 JWT Token 认证（角色为 merchant）
        """
        try:
            user_id = getattr(request, 'user_id', None)
            role = getattr(request, 'role', None)

            if not user_id or role != 'merchant':
                return make_response(code=403, message="权限不足")

            try:
                user = User.objects.get(id=user_id)
                merchant_info = MerchantInfo.objects.get(merchant_id=user_id)
            except (User.DoesNotExist, MerchantInfo.DoesNotExist):
                return make_response(code=403, message="您不是合法的商家用户")

            return DishService.list_categories_with_dishes(str(merchant_info.merchant_id))

        except Exception as e:
            logger.error(f"请求处理失败: {str(e)}", exc_info=True)
            return Response({
                "code": 500,
                "message": f"系统错误：{str(e)}"
            }, status=500)
@extend_schema(
    tags=["菜品管理"],
    parameters=[AUTH_HEADER_PARAM],
    summary="获取菜品详细信息和图片"
)
class GetDishDetailView(APIView):
    def get(self, request, dish_id):
        """
        接口：获取菜品详细信息和图片
        URL 示例：/merchant/dish/detail/123e4567-e89b-12d3-a456-426614174000/
        """
        try:
            user_id = getattr(request, 'user_id', None)
            role = getattr(request, 'role', None)

            if not user_id or role != 'merchant':
                return make_response(code=403, message="权限不足")

            try:
                user = User.objects.get(id=user_id)
                merchant_info = MerchantInfo.objects.get(merchant_id=user_id)
            except (User.DoesNotExist, MerchantInfo.DoesNotExist):
                return make_response(code=403, message="您不是合法的商家用户")

            return DishService.get_dish_detail(dish_id, str(merchant_info.merchant_id))

        except Exception as e:
            return Response({
                "code": 500,
                "message": f"系统错误：{str(e)}"
            }, status=500)


@extend_schema(tags=["菜品管理"], summary="用户端：获取商家分类及菜品（公开信息）")
class PublicListCategoriesWithDishesView(APIView):
    def get(self, request, merchant_id):
        """
        接口：用户端获取某商家的所有分类及对应菜品（仅返回 ID 和名称）
        不需要登录或 Token
        URL 示例：/public/merchant/<merchant_id>/dishes/
        """
        try:
            if not merchant_id:
                return Response({
                    "code": 400,
                    "message": "缺少路径参数 merchant_id"
                }, status=400)

            # 调用服务层，is_public=True 表示只返回公开字段
            return DishService.list_categories_with_dishes(merchant_id)

        except Exception as e:
            return Response({
                "code": 500,
                "message": f"系统错误：{str(e)}"
            }, status=500)


@extend_schema(tags=["菜品管理"], summary="用户端：获取菜品详细信息和图片（无需登录）")
class PublicGetDishDetailView(APIView):
    def get(self, request, merchant_id, dish_id):
        """
        接口：用户端获取菜品详细信息和图片
        URL 示例：/public/merchant/abcd1234-5678-90ef-ghij-klmnopqrstuv/dish/123e4567-e89b-12d3-a456-426614174000/
        """
        try:
            return DishService.get_dish_detail(dish_id=dish_id, merchant_id=merchant_id)

        except Exception as e:
            return Response({
                "code": 500,
                "message": f"系统错误：{str(e)}"
            }, status=500)